/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bff.core.session;


import com.inspur.edp.bff.api.manager.IFSManagerFactory;
import com.inspur.edp.bff.core.manager.FSManager;
import com.inspur.edp.cef.api.session.ICefSession;
import com.inspur.edp.cef.entity.accessor.base.IAccessor;
import com.inspur.edp.commonmodel.core.session.SessionItemRecover;
import com.inspur.edp.commonmodel.core.session.distributed.dac.FuncSessionItemIncrement;
import com.inspur.edp.commonmodel.core.variable.VarBufferManager;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import org.springframework.util.StringUtils;

public class SessionItemRecoverImpl implements SessionItemRecover<BffSessionItem> {

    private static IFSManagerFactory factory;

    static {
        factory = SpringBeanUtils.getBean(IFSManagerFactory.class);
    }

    @Override
    public BffSessionItem buildSessionItem(ICefSession session, String configId) {
        FSManager lcp = (FSManager) factory.getFSManagerByVOId(configId);
        return lcp.buildSessionItem(session);
    }

    @Override
    public void incrementBeforeReset(BffSessionItem item, FuncSessionItemIncrement increment) {
        increment4Variable(item, increment);
//    increment4WeakVariables(item, increment);
    }

    @Override
    public void incrementAfterReset(BffSessionItem item, FuncSessionItemIncrement increment) {
        incrementBeforeReset(item, increment);
    }

    @Override
    public void reset(BffSessionItem bffSessionItem) {
    }

    private void increment4Variable(BffSessionItem item, FuncSessionItemIncrement increment) {
        if (StringUtils.isEmpty(increment.getVarChangeString())) {
            return;
        }
        VarBufferManager manager = item.getVarBufferManager();
        //TODO: 调试看看只读data变不变
        ((IAccessor) manager.getCurrentData())
                .acceptChange(manager.getVarManager().deserializeChange(increment.getVarChangeString()));
    }
}
